package com.xin.data.simbapesa.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewbinding.ViewBinding;


import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.adapter.BindCardAdapter;
import com.xin.data.simbapesa.adapter.ValueAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.base.BaseBindingAdapter1;
import com.xin.data.simbapesa.base.BaseBindingPopup;
import com.xin.data.simbapesa.databinding.SimbaBirthPopBinding;
import com.xin.data.simbapesa.databinding.SimbaCardPopBinding;
import com.xin.data.simbapesa.databinding.SimbaDeleteUserPopBinding;
import com.xin.data.simbapesa.databinding.SimbaGenderPopBinding;
import com.xin.data.simbapesa.databinding.SimbaSelectPopBinding;
import com.xin.data.simbapesa.obj.SimbaInfoData;
import com.xin.data.simbapesa.obj.SimbaValueInfo;
import com.xin.data.simbapesa.obj.SimbaWalletChannel;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class PopUtils {

    @SuppressLint("MissingInflatedId")
    public static void showSelectPop(Activity context, View anchorView, List<SimbaValueInfo> list, String data, int i, int j, PopClickInterface onPopClickInterface) {


        LayoutInflater inflater = LayoutInflater.from(context);


        final BaseBindingPopup<ViewBinding> popWindow = getPopupWindow1(context, SimbaSelectPopBinding.inflate(inflater));

        SimbaSelectPopBinding binding = (SimbaSelectPopBinding) popWindow.binding;

        ValueAdapter valueAdapter = new ValueAdapter(context, list);
        valueAdapter.setData(data);
        binding.listView.setAdapter(valueAdapter);


        BarUtils.setNavigationBarColor(context, android.R.color.white);


        if (list.size() >= 10) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ResUtils.d(R.dimen.dp_300));
            binding.listView.setLayoutParams(layoutParams);
        } else {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            binding.listView.setLayoutParams(layoutParams);
        }


        binding.listView.setOnItemClickListener((parent, view, position, id) -> {
            popWindow.dismiss();
            SimbaValueInfo valueBean = list.get(position);
            if (onPopClickInterface != null) {
                if (j == 0) {
                    onPopClickInterface.onClickListener(valueBean.getTitle(), valueBean.getValue(), i, position);
                } else {
                    onPopClickInterface.onClickListener(valueBean.getTitle(), valueBean.getValue(), i, j);
                }
            }
        });

        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);

        popWindow.setOutsideTouchable(true);


        popWindow.showAtLocation(
                anchorView,
                Gravity.NO_GRAVITY,
                location[0],
                location[1] + anchorView.getHeight()
        );

        binding.tvRoot.setOnClickListener(v -> popWindow.dismiss());

    }

    @SuppressLint("InflateParams")
    public static void showGenderPop(Activity context, View anchorView, List<SimbaValueInfo> list, SimbaInfoData infoData, PopClickInterface onPopClickInterface) {


        LayoutInflater inflater = LayoutInflater.from(context);


        final BaseBindingPopup<ViewBinding> popWindow = getPopupWindow1(context, SimbaGenderPopBinding.inflate(inflater));

        SimbaGenderPopBinding binding = (SimbaGenderPopBinding) popWindow.binding;


        int p = infoData.getIsMan();

        SimbaValueInfo valueInfo1 = list.get(0);
        SimbaValueInfo valueInfo2 = list.get(1);

        binding.tvTitle1.setText(valueInfo1.getTitle());
        binding.tvTitle2.setText(valueInfo2.getTitle());

        binding.tvTitle1Layout.setSelected(false);
        binding.tvTitle2Layout.setSelected(false);
        binding.tvTitle1.setTextColor(Color.parseColor("#666666"));
        binding.tvTitle2.setTextColor(Color.parseColor("#666666"));
        binding.tvBox1.setVisibility(View.GONE);
        binding.tvBox2.setVisibility(View.GONE);

        if (p == 0) {
            if (valueInfo1.getValue().equalsIgnoreCase("female")) {
                binding.tvTitle1Layout.setSelected(true);
                binding.tvTitle1.setTextColor(Color.parseColor("#7D41FF"));
                binding.tvBox1.setVisibility(View.VISIBLE);
            } else {
                binding.tvTitle2Layout.setSelected(true);
                binding.tvTitle2.setTextColor(Color.parseColor("#7D41FF"));
                binding.tvBox2.setVisibility(View.VISIBLE);
            }
        } else if (p == 1) {
            if (valueInfo2.getValue().equalsIgnoreCase("male")) {
                binding.tvTitle2Layout.setSelected(true);
                binding.tvTitle2.setTextColor(Color.parseColor("#7D41FF"));
                binding.tvBox2.setVisibility(View.VISIBLE);
            } else {
                binding.tvTitle1Layout.setSelected(true);
                binding.tvTitle1.setTextColor(Color.parseColor("#7D41FF"));
                binding.tvBox1.setVisibility(View.VISIBLE);
            }
        }


        binding.tvTitle1Layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                binding.tvTitle1Layout.setSelected(true);
                binding.tvTitle2Layout.setSelected(false);
                binding.tvTitle1.setTextColor(Color.parseColor("#2D7314"));
                binding.tvTitle2.setTextColor(Color.parseColor("#666666"));
                binding.tvBox1.setVisibility(View.VISIBLE);
                binding.tvBox2.setVisibility(View.GONE);
                onPopClickInterface.onClickListener("", "", 0, 0);
                popWindow.dismiss();
            }
        });
        binding.tvTitle2Layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                binding.tvTitle1Layout.setSelected(false);
                binding.tvTitle2Layout.setSelected(true);
                binding.tvTitle1.setTextColor(Color.parseColor("#666666"));
                binding.tvTitle2.setTextColor(Color.parseColor("#2D7314"));
                binding.tvBox1.setVisibility(View.GONE);
                binding.tvBox2.setVisibility(View.VISIBLE);
                onPopClickInterface.onClickListener("", "", 0, 1);
                popWindow.dismiss();

            }
        });

        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);

        popWindow.setOutsideTouchable(true);


        popWindow.showAtLocation(
                anchorView,
                Gravity.NO_GRAVITY,
                location[0],
                location[1] + anchorView.getHeight()
        );


        binding.getRoot().setOnClickListener(v -> popWindow.dismiss());

    }


    public static void showBirthPop(Activity context, View anchorView, PopClickInterface1 onPopClickInterface) {


        LayoutInflater inflater = LayoutInflater.from(context);


        final BaseBindingPopup<ViewBinding> popWindow = getPopupWindow(context, SimbaBirthPopBinding.inflate(inflater));

        SimbaBirthPopBinding binding = (SimbaBirthPopBinding) popWindow.binding;


        final int[] currentYear = {Calendar.getInstance().get(Calendar.YEAR)};
        final int[] currentMonth = {Calendar.getInstance().get(Calendar.MONTH) + 1};
        final int[] currentDay = {Calendar.getInstance().get(Calendar.DAY_OF_MONTH)};

        List<String> years = new ArrayList<>();
        List<String> days = new ArrayList<>();

        for (int i = 0; i < 31; i++) {
            String d;
            if (i < 9) {
                d = "0" + (i + 1);
            } else {
                d = (i + 1) + "";
            }
            days.add(d);
        }

        String[] monthArry = context.getResources().getStringArray(R.array.data_arry);
        List<String> months = new ArrayList<>(Arrays.asList(monthArry));

        int cout = 65 - 18;
        int min = currentYear[0] - 65;
        for (int i = 0; i <= cout; i++) {
            String d = (min + i) + "";
            years.add(d);
        }


        binding.tvDate1.setData(days);
        final String[] dayDate = {days.get(0)};
        binding.tvDate1.setSelected("01");

        binding.tvDate2.setData(months);
        final String[] monthDate = {months.get(0)};
        binding.tvDate2.setSelected(0);

        binding.tvDate3.setData(years);
        final String[] yearDate = {years.get(years.size() - 1)};
        binding.tvDate3.setSelected("2007");


        binding.tvColse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                popWindow.dismiss();
            }
        });
        binding.tvBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);

                yearDate[0] = years.get(binding.tvDate3.getmCurrentSelected());
                monthDate[0] = months.get(binding.tvDate2.getmCurrentSelected());
                dayDate[0] = days.get(binding.tvDate1.getmCurrentSelected());

                currentYear[0] = Calendar.getInstance().get(Calendar.YEAR);
                currentMonth[0] = Calendar.getInstance().get(Calendar.MONTH) + 1;
                currentDay[0] = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

                int xDay;
                int xMonth = 0;
                String xDay1;
                String xMonth1;
                String xMonth2;
                int xYear = Integer.parseInt(yearDate[0]);


                if (dayDate[0].startsWith("0")) {
                    xDay = Integer.parseInt(dayDate[0].replace("0", ""));
                } else {
                    xDay = Integer.parseInt(dayDate[0]);
                }
                xDay1 = dayDate[0];

                xMonth1 = monthDate[0];

                for (int i = 0; i < monthArry.length; i++) {
                    if (xMonth1.equals(monthArry[i])) {
                        xMonth = i + 1;
                        break;
                    }
                }

                if (xMonth < 10) {
                    xMonth2 = "0" + xMonth;
                } else {
                    xMonth2 = "" + xMonth;
                }


                if ((xYear == currentYear[0] && xMonth > currentMonth[0]) || (xYear == currentYear[0] && xMonth == currentMonth[0] && xDay > currentDay[0])) {
                    Toast.makeText(context, context.getResources().getString(R.string.birth_error1), Toast.LENGTH_LONG).show();
                    return;
                }
                int tDay = getMonthOfDay(xYear, xMonth);
                LogUtil.e("me", "xDay->" + xDay + ",tDay->" + tDay + ",xMonth->" + xMonth + ",xYear->" + xYear);
                if (xDay > tDay) {
                    Toast.makeText(context, context.getResources().getString(R.string.birth_error2), Toast.LENGTH_LONG).show();
                    return;
                }

                popWindow.dismiss();

                if (onPopClickInterface != null) {
                    onPopClickInterface.onClickListener(xDay1 + "/" + xMonth1 + "/" + xYear, xYear + "-" + xMonth2 + "-" + xDay1);
                }

            }
        });

        popWindow.setOnDismissListener(() -> {
            BarUtils.setNavigationBar(context, true);
        });

        BarUtils.setNavigationBarColor(context, android.R.color.white);

        popWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);

        binding.getRoot().postDelayed(() -> {
            BarUtils.setNavigationBar(context, false);
            BarUtils.setNavigationBarColor(context, android.R.color.white);
        }, 300);


    }

    public static int getMonthOfDay(int year, int month) {
        int day;
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            day = 29;
        } else {
            day = 28;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                return day;

        }
        return 0;
    }


    @SuppressLint("SetTextI18n")
    public static void showBindCardPop(Activity context, View anchorView, List<SimbaWalletChannel> infoList, int cout, PopClickInterface2 onPopClickInterface) {


        LayoutInflater inflater = LayoutInflater.from(context);


        final BaseBindingPopup<ViewBinding> popWindow = getPopupWindow(context, SimbaCardPopBinding.inflate(inflater));

        SimbaCardPopBinding binding = (SimbaCardPopBinding) popWindow.binding;


        BindCardAdapter adapter = new BindCardAdapter(infoList);
        adapter.setOnBtnItemClickListener(new BaseBindingAdapter1.BtnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                adapter.setIndex(position);
                adapter.updateAllData();
            }
        });
        GridLayoutManager manager = new GridLayoutManager(context, 2);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager);
        int d = ResUtils.d(R.dimen.dp_8);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d, d, context));
        binding.recyclerView.setAdapter(adapter);


        binding.tvInput1.setType(PU.P90 + "_1");
        binding.tvInput2.setType(PU.P90 + "_2");

        binding.tvInput1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.tvHit.setVisibility(View.GONE);
                binding.tvInput1.setSelected(false);
                binding.tvInput2.setSelected(false);
                if (!TextUtils.isEmpty(s)) {
                    binding.tvBtn.setSelected(true);
                } else {
                    binding.tvBtn.setSelected(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        binding.tvHit.setVisibility(View.GONE);


        binding.tvBtn.setOnClickListener(v -> {
            if (binding.tvBtn.isSelected()) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P91, "");
                if (onPopClickInterface != null) {
                    String phone = binding.tvInput1.getText().toString();
                    String phone1 = binding.tvInput2.getText().toString();
                    if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(phone1)) {
                        binding.tvHit.setText(context.getResources().getString(R.string.bind_card_toast1));
                        binding.tvHit.setVisibility(View.VISIBLE);
                        binding.tvInput1.setSelected(true);
                        binding.tvInput2.setSelected(true);
                        return;
                    }
                    if (!PhoneUtils.isPhoneNumber(phone)) {
                        binding.tvHit.setVisibility(View.VISIBLE);
                        binding.tvHit.setText(context.getResources().getString(R.string.bind_card_toast2));
                        binding.tvInput1.setSelected(true);
                        binding.tvInput2.setSelected(true);
                        return;
                    }
                    if (!phone.equals(phone1)) {
                        binding.tvHit.setText(context.getResources().getString(R.string.bind_card_toast3));
                        binding.tvHit.setVisibility(View.VISIBLE);
                        binding.tvInput1.setSelected(true);
                        binding.tvInput2.setSelected(true);
                        return;
                    }
                    binding.tvHit.setVisibility(View.GONE);
                    binding.tvInput1.setSelected(false);
                    binding.tvInput2.setSelected(false);
                    int position = adapter.getIndex();
                    SimbaWalletChannel info = infoList.get(position);
                    onPopClickInterface.onClickListener(info, phone);
                }
                popWindow.dismiss();
            }
        });


        BarUtils.setNavigationBarColor(context, android.R.color.white);

        popWindow.setOnDismissListener(() -> BarUtils.setNavigationBar(context, true));

        popWindow.setFocusable(true);
        popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

        popWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);

        binding.tvBtn.postDelayed(() -> {
            BarUtils.setNavigationBar(context, false);
            BarUtils.setNavigationBarColor(context, android.R.color.white);
        }, 300);


        binding.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        PU.userBuriedPoint(PU.P88, "");


    }

    public static TextView showDeleteUserPop(Activity context, View anchorView, PopClickInterface onPopClickInterface) {


        LayoutInflater inflater = LayoutInflater.from(context);


        final BaseBindingPopup<ViewBinding> popWindow = getPopupWindow(context, SimbaDeleteUserPopBinding.inflate(inflater));

        SimbaDeleteUserPopBinding binding = (SimbaDeleteUserPopBinding) popWindow.binding;

        binding.tvCancel.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            popWindow.dismiss();
            if (onPopClickInterface != null) {
                onPopClickInterface.onClickListener("0", "", 0, 0);
            }
        });
        binding.tvOk.setOnClickListener(v -> {
            if (binding.tvOk.isSelected()) {
                ViewUtils.viewScale(v);
                popWindow.dismiss();
                if (onPopClickInterface != null) {
                    onPopClickInterface.onClickListener("1", "", 0, 0);
                }
            }
        });

        BarUtils.setNavigationBarColor(context, android.R.color.white);

        popWindow.setOnDismissListener(() -> BarUtils.setNavigationBar(context, true));

        popWindow.setFocusable(true);
        popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

        popWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);

        return binding.tvOk;

    }


    @NonNull
    private static BaseBindingPopup<ViewBinding> getPopupWindow(Context context, ViewBinding nbinding) {
        return new BaseBindingPopup<>(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, context) {
            @Override
            protected ViewBinding initViewBinding(LayoutInflater inflater) {
                return nbinding;
            }
        };
    }

    @NonNull
    private static BaseBindingPopup<ViewBinding> getPopupWindow1(Context context, ViewBinding nbinding) {
        return new BaseBindingPopup<>(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, context) {
            @Override
            protected ViewBinding initViewBinding(LayoutInflater inflater) {
                return nbinding;
            }
        };
    }

    public interface PopClickInterface {
        void onClickListener(String title, String value, int position, int index);
    }

    public interface PopClickInterface1 {
        void onClickListener(String title, String value);
    }

    public interface PopClickInterface2 {
        void onClickListener(SimbaWalletChannel info, String data);
    }


}
